/*
 * DbSource.cpp
 *
 *  Created on: 2018年1月3日
 *      Author: zhengboyuan
 */

#include "DbSource.h"
#include "TStringUtil.h"

namespace db
{

const char* DbSource::MYSQL = "mysql";
const char* DbSource::ODBC = "odbc";
const char* DbSource::SQLITE3 = "sqlite3";


struct DbSourceTypeName
{
	DbSourceType t;
	const char* name;
};

static DbSourceTypeName s_names[] = {
		{DB_SQLITE, DbSource::SQLITE3},
		{DB_MYSQL, DbSource::MYSQL},
		{DB_ODBC, DbSource::ODBC},
};

const char* DbSource::toString(DbSourceType t)
{
	for (DbSourceTypeName& name : s_names)
	{
		if (name.t == t)
		{
			return name.name;
		}
	}
	return "";
}

bool DbSource::parse(const char* name, DbSourceType& t)
{
    std::string str(name);
	for (DbSourceTypeName& name : s_names)
	{
		if (str == name.name)
		{
			t = name.t;
			return true;
		}
	}
	return false;
}



DbSource::DbSource():
		type(DB_SQLITE),
        port()
{
}

DbSource::~DbSource()
{
}


std::string DbSource::getConnectString()
{
	std::string str;
    if (type == DB_MYSQL)
    {
        if (password.empty())
        {
            str = comn::StringUtil::format("host=%s port=%d db=%s user=%s charset=UTF8",
                ip.c_str(),
                port,
                schema.c_str(),
                user.c_str());
        }
        else
        {
            str = comn::StringUtil::format("host=%s port=%d db=%s user=%s pass=%s charset=UTF8",
                ip.c_str(),
                port,
                schema.c_str(),
                user.c_str(),
                password.c_str());
        }
    }
    else if (type == DB_SQLITE)
    {
    	str = schema;
    }
    return str.c_str();
}

bool DbSource::set(const char* name)
{
	bool got = parse(name, this->type);

    if (type == DB_MYSQL)
    {
        port = 3306;
    }
    return got;
}

bool DbSource::check() const
{
	return type != DB_NONE;
}

bool DbSource::set(const std::string& name)
{
    return set(name.c_str());
}

bool DbSource::isSqlite() const
{
    return this->type == DB_SQLITE;
}


} /* namespace db */
